import { Provide } from '@midwayjs/core'
import { Repository } from 'typeorm'
import { InjectEntityModel } from '@midwayjs/typeorm'
import { RescueInfo } from '../../entities/RescueInfo.entity'

@Provide()
export class RescueInfoService {
  @InjectEntityModel(RescueInfo)
  repo!: Repository<RescueInfo>

  async list(page: number = 1, pageSize: number = 10, filters?: { name?: string; childName?: string }) {
    // 使用QueryBuilder实现关联查询
    const queryBuilder = this.repo.createQueryBuilder('rescue_info')
      // 左连接发起用户
      .leftJoinAndSelect('rescue_info.guardian', 'guardian')
      // 左连接儿童
      .leftJoinAndSelect('rescue_info.child', 'child')
      // 左连接救助记录
      .leftJoinAndSelect('rescue_info.rescueRecords', 'rescueRecords')
      .orderBy('rescue_info.id', 'DESC');

    // 根据救助名称筛选
    if (filters?.name) {
      queryBuilder.andWhere('rescue_info.name LIKE :name', { name: `%${filters.name}%` });
    }

    // 根据儿童姓名筛选
    if (filters?.childName) {
      queryBuilder.andWhere('child.name LIKE :childName', { childName: `%${filters.childName}%` });
    }

    // 分页
    queryBuilder.skip((page - 1) * pageSize).take(pageSize);
    
    // 分别获取数据和总数
    const [data, total] = await queryBuilder.getManyAndCount();

    return {
      total,
      items: data,
    }
  }

  async getById(id: number) {
    return this.repo.findOne({
      where: { id },
      relations: ['guardian', 'child', 'rescueRecords']
    })
  }

  async add(data: Partial<RescueInfo>) {
    const obj = this.repo.create(data)
    return this.repo.save(obj)
  }

  async edit(data: Partial<RescueInfo>) {
    return this.repo.save(data)
  }

  async delete(id: number) {
    return this.repo.delete(id)
  }
}
